
//
const express = require('express')
const models = require('../connect/userdb.js');
const router = express.Router()

// 登录
router.get('/user/login',(request,response)=>{
	// console.log(request.query)
	let list = {
		phone:request.query.phone,
		psd:request.query.psd,
	}
	models.login.findOne({phone:list.phone},(err,data)=>{
		console.log(data);
		if (data == null) {
			response.send({
				'status': 1004,
				'message': '用户未注册',
				'data': []
			})
		} else {
			if(list.phone == data.phone && list.psd == data.psd){
				response.status(200);
				// console.log(data.psd);
				response.send({
					'status': 1000,
					'message': "登录成功",
					"data":data
				})
			}else{
				// response.status(404);
				console.log(err);
				response.send({
					'status': 1001,
					'message': "账号或密码错误",
				})
			}
		}
	})
})

// 注册
//register
router.get('/user/register', (req, res) => {
    models.register.find({
        phone: req.body.phone
    }, (err, data) => {
		console.log(req.body)
        if (err) {
            res.send({
                'status': 1002,
                'message': '查询失败',
                'data': err
            });
        } else {
            console.log('查询成功' + data);
            if (data.length > 0) {
                res.send({
                    'status': 1001,
                    'message': '用户已存在',
                })
            } else {
                let newUser = new models.login({
					phone:req.body.phone,
                    name:req.body.name,
                    psd:req.body.psd
                })
                newUser.save((err, data) => {
                    if (err) {
                        res.send({
                            'status': 1002,
                            'message': '注册失败',
                            'data': err
                        })
                    } else {
						console.log(data)
                        res.send({
                            'status': 1000,
                            'message': '注册成功',
                        })
                    }
                })
            }
        }
    })
})

module.exports = router;